const skinBehavior = require("../../../utils/themeSkin/skinBehavior")
var app = getApp();
var colOneHeight = 0;
var colTwoHeight = 0;
Page({

  behaviors: [skinBehavior],
  /**
	 * 页面的初始数据
	 */
  data: {
    homepageData: {},
    micuid: '',
    message_flag:false,
    catelist: [],
    mainCommentShow: false,
    maincomment: '',
    active: 0,
    catelist_1: [],
    catelist_2: [],
    catelist_3: [],
    catelist_4: [],
    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    loading: false,
    getMoreType: 1,
    self: false,
    stick_type: 1,
    handleTag: false,
    unread_num: "", //消息数量
    message_all: {},
    message_total: 0,
    catelist_upvote_1: [],
    catelist_upvote_2: [],
    imgCount: 0,
    not_pass_1: [],
    not_pass_2: [],
    post_1:[],
    post_2:[],
    imgPath: app.globalData.imgPath
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.themeBaseColor,
    });
    if (options.mid) {
      app._setMid(option.mid);
    }
    if (options.micuid) {
      this.setData({
        micuid: options.micuid,
        self: true
      });
    }
    this.getHomepageData();
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {
    
    this.getMessageData();

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {
    if (this.data.loading) {
      console.log('没有更多数据');
    } else {
      this.getMoreData();
    }
  },

  /** 
	 * 朋友圈
	 */
  onShareTimeline: function () {
    let value = wx.getStorageSync('yz_uid');
    let mid = '';
    if (value) {
      mid = value;
    }
    return {
      title: this.data.homepageData.nickname + '的微社区',
      query: 'micuid=' + this.data.micuid + '&mid=' +
			mid,
    };
  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    return {
      title: this.data.homepageData.nickname + '的微社区',
      path: '/packageC/micro_communities/microhomepage/microhomepage?micuid=' + this.data.micuid + '&mid=' +
				mid
    };
  },
  gotoFanList(e) {
    let actived = e.currentTarget.dataset.actived;
    wx.navigateTo({
      url: '/packageC/micro_communities/microFanlist/microFanlist?uid=' + this.data.micuid+ '&actived='+actived
    });
  },
  getHomepageData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.user.index");
    let dataJson = {};
    if (this.data.micuid) {
      dataJson.uid = this.data.micuid;
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            homepageData: res.data,
            micuid: res.data.uid,
            maincomment: (res.data.signature ? res.data.signature : '')
          });
          if (that.data.homepageData.is_own == 1) {
            that.data.getMoreType = 1;
            that.getClassification();
          } else {
            that.data.getMoreType = 3;
            that.getClassification();
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {}
    });
  },
  getClassification() {
    if (this.data.active == 3) {
      this.setData({
        getMoreType: 4
      })
      this.getMessageData();
      return;
    };
    let that = this;

    let urlStr = app.getNetAddresss("plugin.micro-communities.api.index.getStick");
    that.pageInit();
    let dataJson = {};
    let {
      stick_type
    } = this.data;
    if (this.data.getMoreType == 1) {
      dataJson.uid = that.data.micuid;
      if (stick_type == 0 || stick_type == 1) {
        dataJson.stick_type = stick_type;
      }
    } else if (this.data.getMoreType == 2) {
      dataJson.is_praise = 1;
    } else if (this.data.getMoreType == 3) {
      dataJson.uid = that.data.micuid;
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.data.total_page = res.data.last_page;
          if (that.data.getMoreType == 3) {
            that.setData({
              catelist: res.data.data
            });
          } else if (that.data.getMoreType == 1) {
            if (stick_type == 0) {
              let arr =  [...that.data.not_pass_1,...that.data.not_pass_2];
              let _data = res.data.data;
              let result  = arr.filter(item => {
              let idList = _data.map(val => val.id)
                return idList.indexOf(item.id) == -1
              })
              if(result&&result.length!==0){
                that.formatArr(result,'not_pass_1','not_pass_2');
              }
              that.setData({
                catelist_3: res.data.data
              });
              return;
            }else{
                let arr =  [...that.data.post_1,...that.data.post_2];
                let _data = res.data.data;
                let result  = arr.filter(item => {
                let idList = _data.map(val => val.id)
                 return idList.indexOf(item.id) == -1
                })
                if(result&&result.length!==0){
                  that.formatArr(result,'post_1','post_2');
                }
  
              that.setData({
                catelist_1: res.data.data
              });

            }
            
          } else if (that.data.getMoreType == 2) {
            let arr =  [...that.data.catelist_upvote_1,...that.data.catelist_upvote_2];
            let _data = res.data.data;
            let result  = arr.filter(item => {
            let idList = _data.map(val => val.id)
             return idList.indexOf(item.id) == -1
            })
            if(result&&result.length!==0){
              that.formatArr(result,'catelist_upvote_1','catelist_upvote_2');
            }
            that.setData({
              catelist_2: res.data.data
            });
          }
          console.log(that.data.catelist_3, 3);
          console.log(that.data.catelist_2, 2);
          console.log(that.data.catelist_1, 1);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {}
    });
  },
  attentionBtn() {
    if (this.data.homepageData.is_follow) {
      this.cancelAttention();
    } else {
      this.addAttention();
    }
  },
  cancelAttention() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.user.delFollow");
    let dataJson = {
      uid: this.data.micuid
    };
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            'homepageData.is_follow': false
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {}
    });
  },
  addAttention() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.user.addFollow");
    let dataJson = {
      user_id: this.data.micuid
    };
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            'homepageData.is_follow': true
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {}
    });
  },
  onImageError(options) {
    // let currentId = options.currentTarget.id;
    console.log("图片加载发生错误");
    this.onImageLoad({
      currentTarget: {
        id: options.currentTarget.id
      },
      detail: {
        width: 160,
        height: 160
      },
      type: 'error'
    });
  },
  /**
   * 图片加载函数
   * 图片加载完成后，根据图片的高度，依次往第一列和第二列中推入数据
   */
  onImageLoad(options) {
    let currentId = options.currentTarget.id;
    let imageWidth = options.detail.width; // 图片宽度
    let imageHeight = options.detail.height; // 图片高度
    let activitys = this.data.catelist_2; // 获取所有的数据资源
    if(this.data.active==1){
      activitys = this.data.catelist_3;
    }else if(this.data.active==0){
      activitys = this.data.catelist_1;
    }
    let activityObj = null;
    let scle = (imageWidth / imageHeight);
    for (let i = 0; i < activitys.length; i++) {
      if (activitys[i].id == currentId) {
        if (options.type == 'error' && activitys[i].has_many_image[0]) {
          activitys[i].has_many_image[0].url = `${app.globalData.imgPath}img_404.png`;
        }
        activityObj = activitys[i];
        break;
      }
    }

    this.data.imgCount += 1;
    let activitys1 = this.data.active == 2 ? this.data.catelist_upvote_1 : this.data.active==1? this.data.not_pass_1 : this.data.post_1;
    let activitys2 = this.data.active == 2 ? this.data.catelist_upvote_2 :  this.data.active==1? this.data.not_pass_2 : this.data.post_2;

    if (colOneHeight <= colTwoHeight) {
      colOneHeight += (176 / scle) + 60;
      activitys1.push(activityObj);
    } else {
      colTwoHeight += (176 / scle) + 60;
      activitys2.push(activityObj);
    }

    let data = null;
    if(this.data.active==2){
      data = {   
        catelist_upvote_1: activitys1,
        catelist_upvote_2: activitys2
      }
    }else if(this.data.active==1){
      data = {   
        not_pass_1: activitys1,
        not_pass_2: activitys2
      }
    }else{
      data = {   
        post_1: activitys1,
        post_2: activitys2
      }

    }
    if ((this.data.imgCount >= this.data.catelist_2.length) || (this.data.imgCount>=this.data.catelist_3.length) ||  (this.data.imgCount>=this.data.catelist_1.length)) {
      this.setData({
        showLoading: true
      });
    }

    this.setData(data);
  },
  formatArr(arr,field1,field2){
    arr.forEach(c_item=>{
      if(this.data[field1].findIndex(item=>item.id==c_item.id)!==-1){
        let  index = this.data[field1].findIndex(item=>item.id==c_item.id);
        this.data[field1].splice(index,1);
        this.setData({[field1]:this.data[field1]})
      }else if(this.data[field2].findIndex(item=>item.id==c_item.id)!==-1){
        let  index = this.data[field2].findIndex(item=>item.id==c_item.id);
        this.data[field2].splice(index,1);
        this.setData({[field2]:this.data[field2]})
      }
    })
  },
  jumpDetails(e) {
    let stick_id = e.currentTarget.dataset.stickid;
    wx.navigateTo({
      url: '/packageC/micro_communities/microCommentDetails/microCommentDetails?stickId=' + stick_id
    });
  },
  pageInit() {
    this.data.page = 1;
    this.data.total_page = 0;
    this.data.isLoadMore = true;
    this.data.loading = false;
  },
  getMoreData() {
    const that = this;
    let dataJson = {};
    let {
      stick_type
    } = this.data;
    if (this.data.getMoreType == 1) {
      dataJson.uid = that.data.micuid;
      if (stick_type == 0 || stick_type == 1) {
        dataJson.stick_type = stick_type;
      }
    } else if (this.data.getMoreType == 2) {
      dataJson.is_praise = 1;
    } else if (this.data.getMoreType == 3) {
      dataJson.uid = that.data.micuid;
    }
    that.data.isLoadMore = false; // 防止多次请求分页数据
    let urlStr = "";
    if (that.data.active == 3) {
      urlStr = app.getNetAddresss("plugin.micro-communities.api.message.index")
    } else {
      urlStr = app.getNetAddresss("plugin.micro-communities.api.index.getStick");
    }
    if (this.data.page >= this.data.total_page) {
      that.setData({
        loading: true,
      });
      return;
    } else {
      that.data.page = this.data.page + 1;
      dataJson.page = this.data.page;
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: dataJson,
        success: function (resdata) {
          var res = resdata.data;
          console.log(resdata);
          if (res.result == 1) {
            var myData = res.data.data;
            if (that.data.getMoreType == 4) {
              myData = res.data.stick_comment_list.data
            }
            that.setData({
              handleTag: false
            })
            if (that.data.getMoreType == 3) {
              that.setData({
                catelist: that.data.catelist.concat(myData)
              });
            } else if (that.data.getMoreType == 1) {
              if (stick_type == 0) {
                that.setData({
                  catelist_3: that.data.catelist_3.concat(myData)
                });
                return;
              }
              that.setData({
                catelist_1: that.data.catelist_1.concat(myData)
              });
            } else if (that.data.getMoreType == 2) {
              that.setData({
                catelist_2: that.data.catelist_2.concat(myData)
              });
            } else if (that.data.getMoreType == 4) {
              that.setData({
                catelist_4: that.data.catelist_4.concat(myData)
              });
            }
          } else {
            that.data.page = that.data.page - 1;
            that.data.isLoadMore = false;
            return;
          }
        },
        fail: function (res) {}
      });
    }
  },
  introductionInp() {
    this.setData({
      mainCommentShow: true
    });
  },
  subMainBtn() {
    if (!this.data.maincomment) {
      wx.showToast({
        icon: 'none',
        title: '请留下你的简介吧',
        duration: 1500
      });
      return false;
    }
    let that = this;
    let dataJson = {};
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.user.upSignature");
    dataJson.contents = this.data.maincomment;
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            'homepageData.signature': that.data.maincomment,
            mainCommentShow: false
          });
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });

        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {}
    });
  },
  maincommentinp(e) {
    let val = e.detail.value;
    this.setData({
      maincomment: val
    });
  },
  showClose() {
    this.setData({
      mainCommentShow: false
    });
  },
  getClassificationBtn(e) {
    colOneHeight = 0;
    colTwoHeight = 0;
    let index = e.detail.index;
    this.setData({
      active: index,
      // handleTag: true
    });
    let data= null;
  
    this.setData(data)
    if (index == 2) {
      this.data.getMoreType = 2;
      this.getClassification();
    } else {
      this.data.getMoreType = 1;
      if (index == 0) {
        this.setData({
          stick_type: 1
        });
      } else if (index == 1) {
        this.setData({
          stick_type: 0,
        });
      } else {
        this.setData({
          stick_type: index
        });
      }
      this.getClassification();
    }
  },
  link(e) {
    let params = e.currentTarget.dataset,
      stick_id = params.stickid,
      type = params.type,
      ready = "";
    if (params.ready) {
      ready = params.ready
    }

    if (type == 'all') {
      app._postNetWork({
        url: app.getNetAddresss("plugin.micro-communities.api.message.change-is-read"),
        success: res => {
          if (res.data.result == 1) {
            this.setData({
              unread_num: 0
            })
            app.tips(res.data.msg)
            this.getMessageData();
          } else {
            app.tips(res.data.msg)
          }
        }
      })
    } else if (type == 'single') {
      app._postNetWork({
        url: app.getNetAddresss("plugin.micro-communities.api.message.change-is-read"),
        data: {
          stick_id: stick_id
        },
        success: res => {
          if (res.data.result) {
            wx.navigateTo({
              url: '/packageC/micro_communities/microCommentDetails/microCommentDetails?stickId=' + stick_id
            });
          } else {
            if (ready == 1) {
              wx.navigateTo({
                url: '/packageC/micro_communities/microCommentDetails/microCommentDetails?stickId=' + stick_id
              });
            } else {
              app.tips(res.data.msg)
            }
          }
        }
      })

    }

  },
  getMessageData() {
    this.pageInit();
    app._getNetWork({
      url: app.getNetAddresss("plugin.micro-communities.api.message.index"),
      data: {
        page: this.data.page
      },
      success: res => {
        if (res.data.result == 1) {
          let data = res.data.data.stick_comment_list
          if (this.data.page == 1) {
            this.setData({
              message_total: data.total,
              page: data.current_page,
              total_page: data.last_page,
              unread_num: res.data.data.unread_num,
              catelist_4: data.data
            })
            if (data.data.findIndex(item => item.is_read == 0) !== -1) {
              this.setData({
                message_flag: true
              })
            } else {
              this.setData({
                message_flag: false
              })
            }
          } else {
            this.setData({
              page: data.current_page,
              total_page: data.last_page,
              catelist_4: this.dta.catelist_4.concat(data.data)
            })
          }

        }
      }
    })
  }
});